package com.lai.laiojcodesandbox.controller;

import com.lai.laiojcodesandbox.CodeSandbox;
import com.lai.laiojcodesandbox.CodeSandboxFactory;
import com.lai.laiojcodesandbox.constant.StatusConstant;
import com.lai.laiojcodesandbox.language.codesandbox.JavaCodeSandbox;
import com.lai.laiojcodesandbox.model.ExecuteCodeRequest;
import com.lai.laiojcodesandbox.model.ExecuteCodeResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Slf4j
@RestController("/")
public class MainController {


    @Resource
    private CodeSandboxFactory codeSandboxFactory;

    /**
     * 执行代码
     * @param executeCodeRequest 请求信息
     * @return 执行信息
     */
    @PostMapping("/executeCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest) {
        System.out.println("请求数据为："+executeCodeRequest.toString());

        // 判断请求参数是否为空
        if (executeCodeRequest == null) {
            return ExecuteCodeResponse.fail(StatusConstant.PARAMS_ERROR);
        }
        // 通过语言获取代码沙箱
        String language = executeCodeRequest.getLanguage();
        CodeSandbox codeSandbox = codeSandboxFactory.newInstance(language);

        try{
            // 返回执行结果
            return codeSandbox.executeCode(executeCodeRequest);
        }catch (Exception e){
            // 容器执行错误
            log.error("容器执行错误："+e);
            return ExecuteCodeResponse.fail(StatusConstant.CODESANDBOX_ERROR);
        }

    }
}
